class Search < ActiveRecord::Base
  def users(page)
    @users ||= find_users(page)
  end

  private

  def find_users(page)
    User.paginate(:all,:include=>[:blogs, :exam_results], :conditions => conditions, :page=>page, :per_page=>30)
  end

  def name_conditions
    ["(blogs.profile LIKE ? OR users.login LIKE ? OR users.fname LIKE ? OR users.lname LIKE ?)", "%#{name}%", "%#{name}%", "%#{name}%", "%#{name}%"] unless name.blank?
  end
  def sex_conditions
    case sex
    when 1
      ["users.title = ?", "นาย"]
    when 2
      ["(users.title = ? OR users.title = ?)", "นาง", "นางสาว"]
    end
  end
  def max_age_conditions
    ["( YEAR(CURDATE())-YEAR(users.dob) ) <= ?", max_age] unless max_age.blank?
  end
  def min_age_conditions
    ["( YEAR(CURDATE())-YEAR(users.dob) ) >= ?", min_age] unless min_age.blank?
  end
  def user_type_conditions
    ["users.user_type = ?", user_type ] unless user_type.blank?
  end
  def education_conditions
    ["users.education >= ?", education ] unless education.blank?
  end
  def course1_conditions
    ["(exam_results.course_id=1 AND exam_results.percent >= ?)", course1_score ] unless course1_score.blank?
  end
  def course2_conditions
    ["(exam_results.course_id=2 AND exam_results.percent >= ?)", course2_score ] unless course2_score.blank?
  end
  def course3_conditions
    ["(exam_results.course_id=3 AND exam_results.percent >= ?)", course3_score ] unless course3_score.blank?
  end
  def course4_conditions
    ["(exam_results.course_id=4 AND exam_results.percent >= ?)", course4_score ] unless course4_score.blank?
  end
  def course5_conditions
    ["(exam_results.course_id=5 AND exam_results.percent >= ?)", course5_score ] unless course5_score.blank?
  end

  def conditions
    [conditions_clauses.join(' AND '), *conditions_options]
  end

  def conditions_clauses
    conditions_parts.map { |condition| condition.first }
  end

  def conditions_options
    conditions_parts.map { |condition| condition[1..-1] }.flatten
  end

  def conditions_parts
    private_methods(false).grep(/_conditions$/).map { |m| send(m) }.compact
  end
end
